const koa = require('koa')
const router = require("koa-router")()
const cors = require("koa2-cors");//用来解决跨域
const Top250Model = require("./models/top250")
const koaBody = require("koa-body")
const static = require("koa-static")
const path = require("path")
const fs = require("fs");
const {ObjectId} = require("mongodb")
const app = new koa()
router.get("/top250",async ctx=>{
    var {start,limit} = ctx.query
    if(start == undefined){
        start = 0
    }
    if(limit == undefined){
        limit = 5
    }
    var data = await Top250Model.find().skip(Number(start)).limit(Number(limit))
    var total = await Top250Model.find().count()
    ctx.body = {
        code:200,
        res:data,
        total,
        msg:"GET /top20  success"
    }
})
router.post("/collect/cancel",async ctx=>{
    ctx.set("Access-Control-Allow-Origin","*")
    var id = ctx.request.body.id
    var res = await Top250Model.updateOne({_id:id},{collected:false})
    if(res.acknowledged){
        ctx.body = {
            code:200,
            msg:"取消收藏"
        }
    }else{
        ctx.body = {
            code:400,
            msg:"warning 已经取消收藏，不必重复操作"
        }
    }
})
router.post("/collect",async ctx=>{
    ctx.set("Access-Control-Allow-Origin","*")
    var id = ctx.request.body.id
    var res = await Top250Model.updateOne({_id:id},{collected:true})
    if(res.acknowledged){
        ctx.body = {
            code:200,
            msg:"收藏成功"
        }
    }else{
        ctx.body = {
            code:400,
            msg:"warning 已经收藏，不必重复操作"
        }
    }
})
router.post("/Delete",async ctx=>{
    var title = ctx.request.body.title
    await Top250Model.deleteOne({title:title})
})
router.post("/file",async ctx=>{
    var {title,slogo,evaluate,rating,label,collected} = ctx.request.body
    const file = ctx.request.files.file.path
    const basename = path.basename(file)
    var pic = `${ctx.origin}/${basename}`
    var reader = fs.createReadStream(file)
    var uploadFile = `./static/${basename}`
    var writer = fs.createWriteStream(uploadFile)
    reader.pipe(writer)
    var res = await Top250Model.insertMany({
        title,
        pic,
        slogo,
        evaluate,
        label,
        rating,
        collected:Boolean(collected)
    })
})
router.get("/detail",async ctx=>{
    var id = ctx.query.id.trim()
    var data = await Top250Model.find({_id:ObjectId(id)})
    ctx.body = {
        code:200,
        res:data[0]
    }
})
app.use(koaBody({
    multipart:true,
    formidable:{
        maxFileSize:200*1024*1024,//设置默认上传文件大小
        // 保留文件扩展名
        keepExtensions:true
    }
}))
app.use(static(path.join(__dirname,"static")))
app.use(cors())
app.use(router.routes())
app.listen(8080,()=>{
    console.log("8080端口打开了");
})